import Vue from 'vue';
import VueRouter from 'vue-router';

import _Const from '@/Const';
import { post } from '@/utils/request';
import { getUserMenus } from '@/api/user';
// ********* 子页 *********
import TaskManagement from './src/TaskManagement';
import Range from './src/Range';

const NODE_ENV = process.env.COS_ENV;

/**
 * 路由按需引入
 * 注意：
 *  1. 路由定义的命必须跟接口返回的 menuKey字段值 一致, 并且区分大小写 （比如：menuKey:"Home"  则定义时这么定意思 const Home => import("@/views/home"); ）
 *  2. 接口路由只对主路由(即，path:"/"）下的子路由有效
 */

// ********* 父页 *********
const Index = () => import('@/views/index');
const ErrorPage = () => import('@/views/errorPage');

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'hash',
  base: '/',
  routes: [
    {
      path: '/',
      name: '银企对账管理',
      component: Index,
      redirect: '/range',
      children: [TaskManagement, Range],
    },
    {
      path: '/noPermission',
      name: '无权限',
      component: () => import('@/views/common'),
    },
    {
      path: '*',
      name: '错误页面',
      component: ErrorPage,
    },
  ],
});

function filterList(roleArr: any = [], arr: any = []) {
  roleArr.map((item: any) => {
    if (item.path) {
      item.path.split('#')[1] && arr.push(item.path.split('#')[1]);
    }
    if (item.children && item.children.length) {
      filterList(item.children, arr);
    }
  });
  return arr;
}

const urlList = _Const.UrlList;
const detailList = _Const.DetailList;

router.beforeEach(async (to: any, from, next) => {
  if (urlList.indexOf(to.path) > -1 && NODE_ENV !== 'local') {
    // post(`${window.location.origin}/reconciliation/api/homePage/addViewLog`, { url: `/reconciliation/#${to.path}` });
  }
  let arr: any = (await JSON.parse(sessionStorage.getItem('reconciliationRoleList') as any)) || [];
  if (arr && arr.length === 0) {
    const res: any = (await getUserMenus()) as any;
    res.forEach((el: any, index: any) => {
      if (el && el.code === 'ETMS_RECONCILIATION') {
        const roleList: any = filterList(res[index].children);
        arr = [...roleList, ...detailList];
        sessionStorage.setItem('reconciliationRoleList', JSON.stringify(arr));
      }
    });
  }
  const HomeCompute: any = JSON.parse(sessionStorage.getItem('HomeCompute') as any);
  if (arr && arr.length && !HomeCompute) {
    // 第一次进入时，如果只有局部权限，跳转第一个局部权限页面（sessionStorage存储保证计数器不被初始化）
    sessionStorage.setItem('HomeCompute', JSON.stringify('Y'));
    next();
    return;
  }
  if (to.path === '/noPermission') {
    next();
    return;
  }
  if (arr.indexOf(to.path) > -1 || detailList.indexOf(to.path) > -1) {
    next();
  } else {
    next({ path: '/noPermission' });
    return;
  }
});

router.afterEach((to) => {});

export default router;
